import React, { FC, useMemo } from 'react';
import { SetterHoc } from '../../../common';
import { SelectSetterFun } from '../../select-setter';
import { useRequest } from 'ahooks';
import { API_URL } from '../../config';
import { Request } from '../../../../src/components/utils/request';

export interface IUseTableOptionsParams {
  manual: boolean;
}

export interface IUseTablesParams {
  containAllData?: boolean;
  appId?: string;
}

export async function queryResourceByResourceType(params: { resourceType: any; appId?: string }) {
  return Request.get<any>(API_URL + `/app/resource/query/`, {
    params,
  });
}

/**
 * 获取tables选项
 */
export const useTablesOptions = (
  params?: IUseTablesParams,
  optionsParams?: IUseTableOptionsParams,
) => {
  const { containAllData, appId } = params || {};
  const { manual = false } = optionsParams || {};

  const { loading, run, data }: any = useRequest(
    (currParams?: IUseTablesParams) => {
      const currAppId = currParams?.appId || appId;

      return queryResourceByResourceType({ resourceType: 'TABLE', appId: currAppId });
    },
    {
      manual,
    },
  );

  const options = useMemo(() => {
    const result: any = [];
    if (containAllData) {
      result.push({
        label: '全部表单',
        value: '',
      });
    }
    data?.forEach((item) => {
      result.push({
        label: item.title,
        value: item.id,
      });
    });

    return result;
  }, [data]);

  return { options, queryOptions: run, loading };
};

export interface IAppSelectSetterProps {
  value: string;
  onChange: (value: string) => void;
}

const AppSelectSetterFun: FC<IAppSelectSetterProps> = (props) => {
  // 查询当前应用下的所有的表
  const { options } = useTablesOptions();
  return (
    <SelectSetterFun
      changeReRenderEvent
      onChange={props.onChange}
      options={options}
      value={props.value}
    />
  );
};

export const AppSelectSetter = SetterHoc(AppSelectSetterFun);
